package com.qyer.search.service;/**
 * User: Z J Wu Date: 2016/01/12 Time: 15:05 Package: com.qyer.search.service
 */

import static com.qyer.search.utils.DBUtils.tryConnect;
import static org.apache.commons.dbutils.DbUtils.closeQuietly;

import com.qyer.search.db.DMDBResourceManager;
import com.qyer.search.db.MainDBResourceManager;
import com.qyer.search.enums.KeyType;
import com.qyer.search.model.mutable.PreferDestination;
import com.qyer.search.model.mutable.PreferKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.BitSet;

public class DMDBService {

  private static final Logger LOGGER = LoggerFactory.getLogger(DMDBService.class);

  private static class InnerHolder {

    private static final DMDBService INSTANCE = new DMDBService();
  }

  private DMDBService() {
  }

  public static DMDBService getInstance() {
    return InnerHolder.INSTANCE;
  }

  public final PreferDestination getDestPrefer(PreferKey preferKey){
    long t = System.currentTimeMillis();
    String sql = "";
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    PreferDestination preferDestination = new PreferDestination();
    KeyType keyType = preferKey.getType();
    if(KeyType.DEVICEID == keyType){
      sql = "select type,place_id,weight from tag.dora_place_tag1 where status = 1 and type in (1,2) and deviceid = '" + preferKey.getId() + "';";
    }else if(KeyType.GUID == keyType){
      sql = "select type,place_id,weight from tag.dora_place_tag1 where status = 1 and guid = '" + preferKey.getId() + "';";
    }else if(KeyType.UID == keyType){
      sql = "select type,place_id,weight from tag.dora_place_tag1 where status = 1 and uid = '" + preferKey.getId() + "';";
    }else {
      return preferDestination;
    }
    try {
      System.out.println("sql:"+sql);
      //////////////////////////////////////////////
      conn = tryConnect(DMDBResourceManager.getInstance(), "loadMarketingInfo");
      pstmt = conn.prepareStatement(sql);
      rs = pstmt.executeQuery();
      int type,pid;
      double weight;
      while (rs.next()){
        type = rs.getInt(1);
        pid = rs.getInt(2);
        weight = rs.getDouble(3);
        /*if(preferDestination == null){
          preferDestination = new PreferDestination();
        }*/
        preferDestination.addPlacePrefer(pid, type, weight);
      }
      //////////////////////////////////////////////
    }catch (Exception e){
      e.printStackTrace();
    }
    finally {
      System.out.println("sql:" + (System.currentTimeMillis() - t));
      closeQuietly(conn, pstmt, rs);
      return preferDestination;
    }
  }

  public static void main(String[] args) {
    BitSet bitSet=new BitSet(100000);
    for (int j = 0; j < 10; j++) {
      bitSet.set(j);
    }

    System.out.println(bitSet.length());
    System.out.println(bitSet.size());

  }

}
